package opsControllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"lazyops_go/models"
	"lazyops_go/tools"
	"os"
	"path"
)

type OpsController struct {
	beego.Controller
}




func (c *OpsController) IndexSalt()  {
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")

	label_obj := models.QueryLabelAll()
	var ztree_data_list []models.ZtreeDate
	for _,v :=range label_obj{
		label_id :=v.ID
		host_obj := models.QueryAssetSearchLabel(label_id)
		var ztr_head models.ZtreeDate
		ztr_head.Id = label_id
		ztr_head.Pid = 0
		ztr_head.Name = v.LabelName
		ztr_head.Open = false
		ztree_data_list = append(ztree_data_list, ztr_head)
		for _,vv:= range host_obj{
			var ztree models.ZtreeDate
			ztree.Id = vv.ID*1000
			ztree.Pid = label_id
			ztree.Name = fmt.Sprintf("%s_%s",vv.Ip,vv.HostName)
			ztree.Open = false
			ztree_data_list = append(ztree_data_list, ztree)
		}
	}

	c.Data["ztree_data"] = ztree_data_list
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["label"] = "SaltStack"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "ops/saltjs.html"
	c.TplName = "ops/salt.html"
}

func (c *OpsController) ExecCmd() {
	ip_list := c.GetString("ip_list")
	cmd := c.GetString("cmd")

	check_cmd,err:= models.GetCmdRecord(cmd)
	if err == nil {
		check_cmd.Count += 1
		models.UpdateCmdRecord(check_cmd.ID,check_cmd)
	}else{
		new_obj := models.CmdRecord{}
		new_obj.Count=1
		new_obj.Cmd = cmd
		models.AddCmdRecord(new_obj)
	}

	ret := tools.SaltRunArg(ip_list,"cmd.run",cmd,"root")
	js :=[]byte(ret)
	m := map[string]interface{}{}
	json.Unmarshal(js,&m)
	ret_str := ""
	for _,v := range m["return"].([]interface{}) {
		for k, v1 := range v.(map[string]interface{}) {
			ret_str += fmt.Sprintf("=================== %s （SUCCESS）===================\nCmd：%s\nResult：\n%s\n\n",k,cmd,v1)
		}
	}
	c.Data["json"] = ret_str
	c.ServeJSON()
}

func (c *OpsController) GetCmd() {
	key := c.GetString("key")
	cmd_objs := models.SearchCmdRecord(key)
	var cmd_list []string
	for _,v :=range cmd_objs{
		cmd_list = append(cmd_list,v.Cmd)
	}
	c.Data["json"] = cmd_list
	c.ServeJSON()
}



func (c *OpsController) ExecScript() {
	ip_list := c.GetString("ip_list")
	f,h,_:= c.GetFile("script_file")
	defer f.Close()
	//获取当前项目路径
	dir, _ := os.Getwd()
	save_to_file := path.Join("static/upload/scripts/",h.Filename)
	c.SaveToFile("script_file",save_to_file)
	salt_file := path.Join(dir,save_to_file)
	script_file := fmt.Sprintf("salt://%s",salt_file)
	ret := tools.SaltRunArg(ip_list,"cmd.script",script_file,"root")
	js :=[]byte(ret)
	m := map[string]interface{}{}
	json.Unmarshal(js,&m)
	ret_str := ""
	for _,v := range m["return"].([]interface{}) {
		for k, v1 := range v.(map[string]interface{}) {
			ret_str += fmt.Sprintf("=================== %s （SUCCESS）===================\nScript：%s\nResult：\n%s\n\n",k,script_file,v1)
		}
	}
	c.Data["json"] = ret_str
	c.ServeJSON()
}


func (c *OpsController) UploadFile() {
	ip_list := c.GetString("ip_list")
	to_dir := c.GetString("to_dir")
	f,h,_:= c.GetFile("upload_file")
	defer f.Close()
	//获取当前项目路径
	dir, _ := os.Getwd()
	save_to_file := path.Join("static/upload/files/",h.Filename)
	c.SaveToFile("upload_file",save_to_file)
	src_file := path.Join(dir,save_to_file)
	salt_file := fmt.Sprintf("salt://%s",src_file)
	ret := tools.SaltUploadFile(ip_list,"cp.get_file",salt_file,to_dir,"root")
	js :=[]byte(ret)
	m := map[string]interface{}{}
	json.Unmarshal(js,&m)
	ret_str := ""
	for _,v := range m["return"].([]interface{}) {
		for k, v1 := range v.(map[string]interface{}) {
			ret_str += fmt.Sprintf("=================== %s （SUCCESS）===================\nFile：%s\nResult：\n%s\n\n",k,salt_file,v1)
		}
	}
	c.Data["json"] = ip_list+"\n"+src_file+"\n"+to_dir
	c.ServeJSON()
}





